import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int maxDistance(int[][] grid) {
        int n = grid.length;
        int[][] distance = new int[n][n]; // 陆地到海洋的距离
        boolean[][] visited = new boolean[n][n];
        Queue<int[]> queue = new LinkedList<>();
        // 1、将陆地全部加入到队列中
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                    visited[i][j] = true;
                    distance[i][j] = 0;
                }
            }
        }
        int[] dx = {1,-1,0,0};
        int[] dy = {0,0,1,-1};
        // 2、通过陆地扩展到海洋的距离
        while (!queue.isEmpty()) {
            int[] arr = queue.poll();
            for (int k = 0; k < 4; k++) {
                int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                if (sr >= 0 && sr < n && sc >= 0 && sc < n && !visited[sr][sc]) {
                    distance[sr][sc] = distance[arr[0]][arr[1]] + 1;
                    queue.offer(new int[]{sr, sc});
                    visited[sr][sc] = true;
                }
            }
        }
        int max = 0;
        // 3、寻找出陆地到海洋的最大值，也是海洋到陆地的最大值
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (distance[i][j] > max) {
                    max = distance[i][j];
                }
            }
        }
        return max == 0 ? -1 : max;
    }
}